<?php
class IeitemsController extends CommonController
{
	public function index()
	{
		$ieitemsModelCls = new IeitemsModel($this->uid);
		$this->view->assign('Ieitems', $ieitemsModelCls->getAll());
		$this->view->assign('TreeData', $ieitemsModelCls->getTree());
		$this->view->assign('title', '收支项目管理');
		$this->view->setPlace('content', 'place/ieitems');
		$this->view->display();
	}
	
	/**
	 * 添加收支类型
	 */
	public function add()
	{
		$do = Functions::gpc('do', 'p');
		$ieitemsModelCls = new IeitemsModel($this->uid);
		if($do == 'save')
		{
			$itemType = Functions::sqlgpc('ItemType', 'p');
			$pid = Functions::sqlgpc('PID', 'p');
			if($itemType == 'PID')
			{
				$parent = $ieitemsModelCls->getById($pid);
				if(empty($parent))
				{
					$this->_optComplete(false, '?m=ieitems&a=add', '请选择从属分类');
				}
				$itemType = $parent['ItemType'];
			}
			else 
			{
				$pid = 0;
			}
			$data['ItemType'] = $itemType;
			$data['PID'] = $pid;
			$data['ItemName'] = Functions::sqlgpc('ItemName', 'p');
			$data['Status'] = 1;
			$data['CreateDate'] = time();
			$data['Remark'] = Functions::sqlgpc('Remark', 'p');
			if(!$ieitemsModelCls->add($data))
			{
				$this->_optComplete(false, '?m=ieitems&a=add', '内部错误');
			}
			else
			{
				$this->_optComplete(true, '?m=ieitems', '成功');
			}
		}
		$aLevel = $ieitemsModelCls->getALevel();
		$this->view->assign('ALevel', $aLevel);
		
	    if($this->isAjax)
		{
		    $this->view->setUseLayout(false);
		}
		else
		{
		    $this->view->setPlace('content', 'page/ieitems/add');
		}
		$this->view->assign('title', '增加收支项目');
		$this->view->display();
	}
	
	public function edit()
	{
	    $do = Functions::gpc('do', 'p');
	    $ieitemsModelCls = new IeitemsModel($this->uid);
		if($do == 'save')
		{
		    $aid = Functions::sqlgpc('aid', 'p');
		    $item = $ieitemsModelCls->getById($aid);
		    if(empty($item)) $this->_optComplete(false, '?m=ieitems', '收支项目不存在');
		    
		    $data['ItemName'] = Functions::sqlgpc('ItemName', 'p');
		    $data['Remark'] = Functions::sqlgpc('Remark', 'p');
		    
		    if(!$ieitemsModelCls->edit($aid, $data))
		    {
		        $this->_optComplete(false, '?m=ieitems&a=edit&aid='.$aid, '内部错误');
		    }
		    $this->_optComplete(true, '?m=ieitems', '修改完成');
		}
		
		$aid = Functions::gpc('aid', 'g');
		$item = $ieitemsModelCls->getById($aid);
		if(empty($item)) $this->_optComplete(false, '?m=ieitems', '收支项目不存在');
		$this->view->assign('Item', $item);
	    if($this->isAjax)
		{
		    $this->view->setUseLayout(false);
		}
		else
		{
		    $this->view->setPlace('content', 'page/ieitems/edit');
		}
		$this->view->assign('title', '修改收支项目');
		$this->view->display();
	}
	
	public function __destruct()
	{
		//echo 'index controller destruct!<br />';
	}
}